

import java.util.Iterator;
import java.util.List;

import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import friendShips.User;



@Path("/users")
public class UsersQuery {
    @GET
    @Produces("text/html")
    public String getUser(@QueryParam("userName") @DefaultValue("no") String userName,
    					  @QueryParam("password") @DefaultValue("0") String password) {
    	
		 User user = new User();
		 SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); 
		 Session session = sessionFactory.openSession();
		 UserManager manager = new UserManager(session); 
		 Query query = session.createQuery("from User user where user.email = :newEmail AND user.password = :newPassword");
		 query.setParameter("newEmail", userName);
		 query.setParameter("newPassword", password);
		 List <User>list = query.list();
		 
		 
		 if (list.size()==1)
		 {
			Iterator<User> it=list.iterator();
			User tempUser= new User();
			tempUser=it.next();
			tempUser.setOnline(true);
			manager.updateUser(tempUser);
			session.flush();
			return "OK";
		 }
		 // check if email exists
		 query = session.createQuery("from User user where user.email = :newEmail");
		 query.setParameter("newEmail", userName);
		 list = query.list();
		 //it=list.iterator();
		 if (list.size()==0)
		 {
			return "NEW";
		 }
		 
		 return "BAD";
    }
}
